const express = require("express");
const userRouter = express.Router();
const DB = require("./../db/config");
const upload = require("./../db/uploadconfig");
const myjwt = require("jsonwebtoken");
module.exports = userRouter;

/**
 * @name '1.用户登录接口'
 * @url '/user/login'
 * @method 'post'
 * @params  username {String},用户账号 ，required
 * @params password {String}, 密码 ，required
 * @return {uid,...}, 用户的相关信息
 */
userRouter.route("/user/login").post(function (req, res) {
  let { username, password } = req.body;
  let sql = "select * from  users where uaccess = ? and upassword = ?;";
  let prams = [username, password];
  let cb = (err, data) => {
    if (err == null && data.length === 1 && data[0].ustate === "1") {
      // 登录成功时，给session动态添加一个属性user，值是当前用户这个对象 。
      req.session.user = data[0];
      //三个参数， 1. 数据, 2. 密钥  3.选项设置
      let token = myjwt.sign({ user: username }, "laowenzi", {
        expiresIn: "20s",
      });

      res.json({
        code: 0,
        msg: "登录成功",
        data: data[0],
        token,
      });
    } else {
      res.json({
        code: 4001,
        msg: "登录失败",
      });
    }
  };

  DB.connect(sql, prams, cb);
});

// 2. 添加用户 resetful标准，get,post,put,delete

// userRouter.post("/user/add", upload.single('uphoto'), function(req, res){
//   console.log(req.body)  //接收表单其它值
//   console.log(req.file)  // 单文件上传时使用file属性
//   // console.log(req.files) // 多文件上传时使用files属性

// })
userRouter
  .route("/user/add")
  .post(upload.single("uphoto"), function (req, res) {
    //前端是AJAX请求，后端尽量不要响应字符串回去。
    // if (!req.session.user) {

    //   res.json({
    //     code: 4002,
    //     msg: '请求失败，原因：没有登录或者登录session过期。'
    //   });
    //   return;

    // };

    let { uaccess, uname, upassword, usex, usid, utel } = req.body;
    // console.log(req.body)  //接收表单其它值,除上传的文件以外的
    // console.log(req.file)  // 单文件上传时使用file属性
    let uphoto = req.file.filename;

    let sql = `insert into users values(null,?,?,?,?,?,?,?,default);`;
    let params = [uaccess, uname, upassword, usex, usid, utel, uphoto];
    let cb = (err, data) => {
      console.log(err);
      console.log(data);
      if (err === null) {
        res.json({
          code: 0,
          msg: "添加用户成功",
        });
      } else {
        res.json({
          code: 4001,
          msg: "添加用户失败",
        });
      }
    };
    DB.connect(sql, params, cb);
  });

// 获取所有用户接口，后端分页
/**
 * @url: '/user/getAll'
 * @params pageNow {Number} required 当前第几页
 * @params pageSize {Number} required 每页几条
 * @return [] {Array}
 */

userRouter.route("/user/getAll").get(function (req, res) {
  /* let token1 = req.query.token; // /user/getAll?token=xxcvs&pageNow=value&pageSize=value;
    // console.log("token做参数时:",token1)
    let token = req.headers.token; //  xhr.setRequestHeader('token',sessionStorage.getItem('token'))
    // console.log("token::::::",token)

    try{
      let result = myjwt.verify(token, 'laowenzi');
      console.log(result) //如果verify()解密成功，result就可以看到传给客户端的数据
      // 如果失败，则抛出一个错误异常，让下面的Catch()捕获到错误；

    }catch(err){
      console.log("err++++++++++++++",err)
      res.json({code: 40005,msg:'token认证失败，请重新登录'});
      return;
    } */

  let { pageNow, pageSize } = req.query;
  if (!pageNow && !pageSize) {
    // 返回所有数据，让前端自己分页去~~~
    let sql = "select * from users;";
    let cb = (err, data) => {
      if (!err) {
        res.json({ code: 0, msg: "查询所有用户成功", data });
      } else {
        res.json({ code: 4002, msg: "查询所有用户失败", data });
      }
    };
    DB.connect(sql, [], cb);
  } else {
    // 后端做分页
    let startIndex; //每页开始的索引
    startIndex = (pageNow - 1) * pageSize;
    pageSize = Number(pageSize);
    let sql = `SELECT * FROM users LIMIT ?,?;`;
    sql += "select count(*) as count from users;";
    let params = [startIndex, pageSize];

    let cb = (err, data) => {
      console.log(err);
      // console.log(data); // [[],[{count:6}]]

      if (err === null) {
        //从二维数组中，分别拿出数据，拼成要响应给前端的数据。
        res.json({
          code: 0,
          msg: "查询成功",
          data: data[0],
          count: data[1][0].count,
        });
      } else {
        res.json({ code: 40001, msg: "查询失败" });
      }
    };
    DB.connect(sql, params, cb);
  }
});

// 修改用户状态
userRouter.route("/user/modifyState").post(function (req, res) {
  let ustate = req.body.ustate;
  let uid = req.body.uid;
  let sql = "update users set ustate = ? where uid = ?;";
  let params = [ustate, Number(uid)];
  let cb = (err, data) => {
    console.log(err);
    console.log(data);

    if (err === null) {
      res.json({
        code: 0,
        msg: "修改状态成功",
      });
    } else {
      res.json({
        code: 40001,
        msg: "修改状态失败",
      });
    }
  };
  DB.connect(sql, params, cb);
});

// 删除一个用户
userRouter.route("/user/delete").post((req, res) => {
  // console.log(req.body)
  let uid = Number(req.body.uid);
  if (uid === 1) {
    res.json({
      code: 4001,
      msg: "管理员账号不能删除",
    });
    return;
  }

  let sql = `delete from users where uid = ?;`;
  let params = [uid];
  let cb = (err, data) => {
    if (err === null) {
      res.json({
        code: 0,
        msg: "删除成功",
      });
    } else {
      res.json({
        code: 40001,
        msg: "删除失败",
      });
    }
  };
  DB.connect(sql, params, cb);
});

// 修改用户信息的接口
userRouter
  .route("/user/modifyUserInfo")
  .post(upload.single("uphoto"), function (req, res) {
    // single('uphoto')中的'uphoto'就是参数名
    console.log(req.body)
    console.log(req.file)  // 没有传文件时，是undefined,反之是 一个对象。
    let { uid, uaccess, upassword, uname, usex, utel, usid, ustate } = req.body;
	if(!uid){
		res.json({ code: 4003, msg: "没有uid" });
		return;
	}
    let uphoto = ""; //默认设置为空字符串，
    if (req.file !== undefined) {
      uphoto = req.file.filename; // 设置为上传的文件名。
    }
    // 判断有没有传uphoto的值？
    let sql = `update users set upassword = ?, uname = ?, usex = ?, utel = ?,usid = ? ${
      uphoto !== "" ? ",uphoto = ?" : ""
    } where uid = ?;`;
    // 数组初始化，
    let params = [upassword, uname, usex, utel, usid];
    // 判断要不要添加uphoto
    uphoto !== "" && params.push(uphoto);
    // 最后，添加uid.
    params.push(uid);

    // console.log(sql)
    // console.log(params)
    let cb = (err, data) => {
      console.log(err);
      if (err === null) {
        res.json({ code: 0, msg: "修改成功" });
      } else {
        res.json({ code: 4001, msg: "修改失败" });
      }
    };

    DB.connect(sql, params, cb);
  });

// 给用户设置角色
/**
 * @params uid, {Number},required
 * @params ridList, {Array},required,不能为空数组
 */
userRouter.route("/user/addRoles").post(async (req, res) => {
  let { uid, ridList } = req.body;
  // 1、选择执行删除数据
  new Promise((resolve, reject) => {
    let sql = "delete from userroletable where uid = ?;";
    let pramas = [uid];
    let cb = (err, data) => {
      if (err === null) {
        resolve("删除数据成功");
      } else {
        reject("删除数据失败");
      }
    };
    DB.connect(sql, pramas, cb);
  })
    // 2. 在then()执行插入数据
    .then((result) => {
      console.log(result); //'ok'
      // 在then()中，如果还需要把一个结果传给下一个then()中，就需要使用return;
      return new Promise((resolve, reject) => {
        if (ridList === undefined) {
          resolve("用户设置角色成功");
        } else {
          let sql = "insert into userroletable values ";
          let params = [];
          let textArr = []; // 目的数据：['(NULL, ?,?)','(NULL, ?,?)']
          ridList.forEach((item) => {
            textArr.push("(NULL, ?, ?)");
            params.push(Number(uid));
            params.push(Number(item));
          });
          sql = sql + textArr.join(",") + ";";
          let cb = (err, data) => {
            if (err === null) {
              // res.json({ code: 0, msg: '给用户设置角色成功' })
              resolve("给用户设置角色成功");
            } else {
              // res.json({ code: 40002, msg: '给用户设置角色失败' })
              reject("给用户设置角色失败");
            }
          };

          DB.connect(sql, params, cb);
        }
      });
    })
    // 3.所有操作成功时，响应客户端的请求
    .then((result2) => {
      console.log("----------+++++++++++", result2);
      res.json({ code: 0, msg: result2 });
    })
    // 4. 所有失败时，响应客户端的请求
    .catch((err) => {
      console.log(err);
      res.json({ code: 40001, msg: err });
    });
  // 演示finally的执行。
  // .finally(()=>{
  //   console.log("设置用户角色结束")
  // })

  /* 
     let { uid, ridList } = req.body;
        // console.log(req.body);// { uid: '1', ridList: [ '1', '2' ] }
    
        let sql = 'insert into userroletable values ';
        let params = [];
        let textArr = []; // 目的数据：['(NULL, ?,?)','(NULL, ?,?)']
        ridList.forEach(item => {
          textArr.push('(NULL, ?, ?)')
          params.push(Number(uid))
          params.push(Number(item))
        });
        // console.log(textArr.join(","))
        // console.log(params)
        sql = sql + textArr.join(",") + ";"  //完整SQL语句: "INSERT INTO userroletable VALUES (NULL, ?, ?),(NULL, ?, ?),(NULL, ?, ?),(NULL, ?, ?);"
        // console.log(sql)  //一定要先检查SQL语句语法 
    
        let cb = (err, data) => {
          if (err === null) {
            res.json({ code: 0, msg: '给用户设置角色成功' })
          } else {
            res.json({ code: 40002, msg: '给用户设置角色失败' })
          }
        };
    
        DB.connect(sql, params, cb);
     */
});

// 获取一个用户的分配的角色列表
userRouter.route("/user/getRoles").post((req, res) => {
  let uid = req.body.uid;
  let sql = ` SELECT rid FROM userroletable WHERE uid = ?;`;
  let params = [uid];
  let cb = (err, data) => {
    if (err === null) {
      res.json({ code: 0, msg: "获取用户的角色列表成功", data });
    } else {
      res.json({ code: 40001, msg: "获取用户的角色列表失败" });
    }
  };
  DB.connect(sql, params, cb);
});

// 搜索账号和名称
userRouter.route("/user/search").post((req, res) => {
  let text = req.body.text;
  let sql = `select * from users where uaccess like ? or uname like ?;`;
  let param = ["%" + text + "%", "%" + text + "%"];
  let cb = (err, data) => {
    if (err === null) {
      res.json({ code: 0, msg: "搜索成功", data });
    } else {
      res.json({ code: 4001, msg: "搜索失败" });
    }
  };

  DB.connect(sql, param, cb);
});
